package cz.acies.data.dao;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.map.CaseInsensitiveMap;
import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.BeanProcessor;

public class DefaultRowProcessor extends BasicRowProcessor {

	public DefaultRowProcessor() {
		super();
	}

	public DefaultRowProcessor(BeanProcessor convert) {
		super(convert);
	}

	@Override
	public Map<String, Object> toMap(ResultSet rs) throws SQLException {
		Map<String, Object> result = new CaseInsensitiveMap<String, Object>();
		//Map<String, Object> result = new LinkedHashMap<String, Object>();
		ResultSetMetaData rsmd = rs.getMetaData();
		int cols = rsmd.getColumnCount();
		for (int i = 1; i <= cols; i++) {
			int colType = rsmd.getColumnType(i);
			String colName = rsmd.getColumnName(i);
			Object value = rs.getObject(i);
			switch (colType) {
				case Types.DATE: {
					if (value instanceof java.util.Date) {
						try {
							Date date = ((Date)value);
							//long t = date.getTime();
						} catch (Exception exc) {
							System.out.println("ERROR: " + exc.getMessage());
							value = Timestamp.valueOf("9999-01-01");
						}
					} else {
						value = java.sql.Date.valueOf("2099-01-01");
					}
					break;
				}
				case Types.TIMESTAMP: {
					if (value instanceof Timestamp) {
						try {
							Date date = ((Date)value);
							//long t = date.getTime();
						} catch (Exception exc) {
							System.out.println("ERROR: " + exc.getMessage());
							value = Timestamp.valueOf("9999-01-01 00:00:00");
						}
					} else {
						value = Timestamp.valueOf("9999-01-01 00:00:00");
					}
					break;
				}
				default: break;
			}
			result.put(colName, value);
		}
		return result;
	}

	@Override
	public Object[] toArray(ResultSet arg0) throws SQLException {
		return super.toArray(arg0);
	}

	@Override
	public <T> T toBean(ResultSet rs, Class<T> type) throws SQLException {
		return super.toBean(rs, type);
	}

	@Override
	public <T> List<T> toBeanList(ResultSet rs, Class<T> type) throws SQLException {
		return super.toBeanList(rs, type);
	}	
}
